package KademliaDht

import (
	"container/vector"
	"math"
)

type KadBucket struct {
	MinDistance	uint64
	MaxDistance	uint64
	K			int
	Vector		*vector.Vector
}

func New_KadBucket( index int, k int ) *KadBucket {
	minDistance := uint64( math.Pow( 2, float64( index ) ) )
	maxDistance := uint64( math.Pow( 2, float64( ( index + 1 ) ) ) - 1 )
	return &KadBucket{ minDistance, maxDistance, k, new( vector.Vector ) }
}

func ( k *KadBucket ) At ( index int ) *KadContact {
	return k.Vector.At( index ).( *KadContact )
}

func ( k *KadBucket ) Len () int {
	return k.Vector.Len()
}

func ( k *KadBucket ) Spotted ( c * KadContact ) {
	exists, pos := k.search( c )
	if ( exists ) {
		k.Vector.Delete( pos )
		k.Vector.Push( c )
	} else {
		if ( k.Vector.Len() < k.K ) {
			k.Vector.Push( c )
		} else { // TODO: Else ping last seen contact and replace it if dead
			k.Vector.Pop()
			k.Vector.Push( c )
		} 
	}
}

func ( k *KadBucket ) search ( c * KadContact ) (exists bool, pos int) {
	for i := 0; i < k.Vector.Len(); i++ {
		ic := k.Vector.At( i ).(* KadContact)
		if ( c.Id == ic.Id ) {
			return true, i
		}
	}
	return false, -1
}

func ( k *KadBucket ) GetSlice () []*KadContact {
	ret := make( []*KadContact, 0, 0)
	for i := 0; i < k.Vector.Len(); i++ {
		ret = append( ret, k.Vector.At( i ).( *KadContact ) )
	}
	return ret
}

